<template>
  <div class="pane">
    <div class="pane-left-wrap">
      <div class="pane-top-wrap">
        <el-button @click="handleCreateMenu" type="primary">新增菜单</el-button>
        <el-button @click="applyToMenu" type="warning">发布应用</el-button>
      </div>
      <x2-table
        highlight-current-row
        :height="'calc(100vh - 205px)'"
        @handleRowAction="handleRowAction"
        border
        :data="dataList"
        :columns="tableConfig.fields"
        @row-click="handleSelectMenu"
      >
      </x2-table>
    </div>
    <div v-if="isSelectedMenu" class="pane-right-wrap">
      <div class="pane-right-top-row">
        <x2-space></x2-space>
        <el-button @click="handleSubmit" type="primary">保存提交</el-button>
      </div>

      <div v-if="!isNewRecord" class="pane-right-top-row-flex">
        <span style="font-weight: bold; font-size: 14px; color: #666; margin-right: 12px">菜单定位</span>
        <div class="menu-path-map">{{ currentMenuMap }}</div>
        <el-button @click="handlePathManage" type="primary">菜单调整</el-button>
      </div>
      <x2-form ref="editform" :is-new="isNewRecord" :form-config="formConfig"></x2-form>
    </div>
  </div>
</template>

<script>
import { formConfig, tableConfig } from './config'
import PathSelect from './pathSelect.vue'

function findMenu(id, menu) {
  for (let item of menu) {
    if (item.name == id) return item
    if (item.children && item.children.length > 0) {
      const tmp = findMenu(id, item.children)
      if (tmp) return tmp
    }
  }
  return null
}

function getMenuMap(id, menu) {
  for (let item of menu) {
    if (item.name == id) return item.meta.title
    if (item.children && item.children.length > 0) {
      const tmp = getMenuMap(id, item.children)
      if (tmp) return [item.meta.title].concat(tmp)
    }
  }
  return null
}

export default {
  name: 'AppPublish',
  components: { PathSelect },
  props: {
    id: { type: String, default: '' },
  },
  data() {
    return {
      dataList: [],
      tableConfig,
      formConfig,
      currentMenu: {},
      isNewRecord: false,
      ddlScenario: [],
      currentMenuMap: '',
    }
  },
  computed: {
    isSelectedMenu() {
      return JSON.stringify(this.currentMenu) == '{}' ? false : true
    },
  },
  mounted() {
    this.handleRefresh()
  },
  methods: {
    async getScenarioDDLB() {
      if (this.ddlScenario.length > 0) return this.ddlScenario
      const res = await this.$request({
        url: '/lowcode/getDataBySql',
        method: 'post',
        data: { sqlid: '应用下的页面列表(下拉项)', where: `apl.appId='${this.id}'` },
      })
      return res.list
    },
    async updateScenarioDDLB() {
      const ddlb = await this.getScenarioDDLB()
      console.log('ddlb', ddlb)
      this.$refs.editform._set_asyncOpt('scenarioId', ddlb)
    },
    handleRowAction(e, row, action) {
      console.log('handleRowAction', e, row, action)
    },
    async isExistNotSave(item = null) {
      try {
        if (this.isNewRecord) {
          const res = await this.$confirm('有一个菜单正在编辑，是否继续当前操作？', '注意', { type: 'warning' })
        } else if (!this.isSelectedMenu) {
          return true
        } else {
          if (item != null && this.currentMenu.id == item.id) return false
          if (this.$refs.editform.isModify()) {
            const res = await this.$confirm('有一个菜单正在编辑，是否继续当前操作？', '注意', { type: 'warning' })
          }
        }
        return true
      } catch (e) {
        console.log(e)
        return false
      }
    },
    async handleCreateMenu() {
      const isContinue = await this.isExistNotSave()
      if (!isContinue) return
      this.isNewRecord = true
      const newMenu = {
        id: this.$uuid(),
        appId: this.id,
        menuName: '',
        scenarioId: '',
        roles: '',
        isLock: 'N',
      }
      this.currentMenu = newMenu
      setTimeout(() => {
        this.$refs.editform.init(newMenu)
        this.updateScenarioDDLB()
      }, 0)
    },
    async handlePathManage() {
      const res = await this.$showDialog({
        component: PathSelect,
        dialogParams: {
          title: '应用菜单管理',
          width: '500px',
          'close-on-click-modal': false,
          'show-close': false,
        },
        childParams: {
          id: this.currentMenu.id,
        },
      })
      if (res.closeType == 'confirm') {
        this.updateMenuMap()
      }
    },
    async updateMenuMap() {
      const res = await this.$request({
        url: '/lowcode/getDataBySql',
        method: 'post',
        data: { sqlid: '文档内容', where: `dkey='appMenuList'` },
      })
      const _appMenuList = JSON.parse(res.list[0]['dvalue'])
      const m = getMenuMap(this.currentMenu.id, _appMenuList)
      this.currentMenuMap = m.join(' > ')
      if (m[m.length - 1] != this.currentMenu.menuName) {
        const { id } = this.currentMenu
        const param = { id, menuName: m[m.length - 1] }
        const data = [
          {
            tableName: 'appMenuList',
            action: 'update',
            dataList: [param],
          },
        ]
        const updateRes = await this.$request({
          url: '/lowcode/commonUpdate',
          method: 'post',
          data,
        })
        this.currentMenu.menuName = m[m.length - 1]
        setTimeout(() => {
          this.$refs.editform.init(this.currentMenu)
          this.updateScenarioDDLB()
        }, 0)
      }
    },
    async handleSelectMenu(item) {
      const isContinue = await this.isExistNotSave(item)
      if (!isContinue) return

      const res = await this.$request({
        url: '/lowcode/getDataBySql',
        method: 'post',
        data: { sqlid: '应用下的菜单列表', where: `aml.id='${item.id}'` },
      })

      this.currentMenu = res.list[0]
      this.updateMenuMap()
      this.isNewRecord = false
      setTimeout(() => {
        this.$refs.editform.init(this.currentMenu)
        this.updateScenarioDDLB()
      }, 0)
    },
    async handleRefresh() {
      const res = await this.$request({
        url: '/lowcode/getDataBySql',
        method: 'post',
        data: { sqlid: '应用下的菜单列表', where: `aml.appId='${this.id}'` },
      })
      this.dataList = res.list
      if (res.list.length > 0 && !this.isSelectedApp) {
        await this.handleSelectMenu(res.list[0])
      }
    },
    async applyToMenu() {},
    async handleSubmit() {
      const res = await this.$refs.editform.submit()
      if (res) {
        const items = await this.$refs.editform.getData()
        this.updateToAppMenuList(items)
        if (this.isNewRecord) this.isNewRecord = false
        await this.handleRefresh()
      }
    },
    async updateToAppMenuList(items) {
      const res = await this.$request({
        url: '/lowcode/getDataBySql',
        method: 'post',
        data: { sqlid: '文档内容', where: `dkey='appMenuList'` },
      })
      const _appMenuList = JSON.parse(res.list[0]['dvalue'])
      const m = findMenu(items.id, _appMenuList)
      if (!m) {
        _appMenuList[_appMenuList.length - 1].children.push({
          path: items.id,
          component: '',
          redirect: `/dev-platform/pagerun/${items.scenarioId}`,
          props: true,
          name: items.id,
          isPage: true,
          meta: {
            title: items.menuName,
          },
          children: null,
        })
      } else {
        m.redirect = `/dev-platform/pagerun/${items.scenarioId}`
        m.meta.title = items.menuName
      }

      const param = {
        dkey: 'appMenuList',
        dvalue: JSON.stringify(_appMenuList),
      }

      const data = [
        {
          tableName: 'z_doc',
          action: 'update',
          dataList: [param],
        },
      ]
      const updateRes = await this.$request({
        url: '/lowcode/commonUpdate',
        method: 'post',
        data,
      })
    },
  },
}
</script>
<style scoped>
.pane {
  display: flex;
}
.pane-left-wrap {
  flex: 1;
  height: calc(100vh - 160px);
}
.pane-right-wrap {
  width: 460px;
  height: calc(100vh - 160px);
  display: flex;
  flex-direction: column;
}
.pane-top-wrap {
  margin: 0 0 10px 0;
  height: 28px;
  width: 100%;
  display: flex;
  align-items: center;
}
.pane-right-top-row {
  height: 38px;
}
.pane-right-top-row-flex {
  height: 37px;
  padding: 0 6px 0 12px;
  display: flex;
  align-items: center;
  background: #efefef;
}
.menu-path-map {
  font-size: 13px;
  color: #777;
  flex: 1;
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 使用省略号表示溢出文本 */
  white-space: nowrap; /* 防止文本换行 */
}
</style>
